/*
 * Functions to make a connection,
 * request a token if not in cookie
 * send and receive Channel messages
 */

//general ajax function for all requests 
function makeRequest(url,async) {
	var httpRequest;
	if (window.XMLHttpRequest) {
		// Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
	}
	
	if (!httpRequest) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	httpRequest.open('POST',url,async);
	httpRequest.send();
	return httpRequest;
}

requestToken = function(){
	var channelCookieExists = new Boolean(document.cookie.indexOf("chtoken") >= 0);
	if (channelCookieExists==true) {
		//Use the cookie's data
		openChannel(readCookie("chtoken"));
	} else {
		var getTokenURI = '/gettoken?userId=' + viewer ;
		var httpRequest = makeRequest(getTokenURI,true);
		httpRequest.onreadystatechange = function(){
			if (httpRequest.readyState === 4) {
				if (httpRequest.status === 200) {
					//Create the cookie
					writeCookie("chtoken",httpRequest.responseText,(2/24));
					//Open the channel
					openChannel(httpRequest.responseText);
				}
			}
		}
	}
	resize();
	iniOptionsMenu();
};

openChannel = function(token) {
	var channel = new goog.appengine.Channel(token);
	var socket = channel.open();
	socket.onopen = onSocketOpen;
	socket.onmessage = onSocketMessage;
	socket.onerror = onSocketError;
	socket.onclose = onSocketClose;
};

onSocketError = function(error){
	requestToken();
	var sendMessageURI = '/logger?code=3&status=ChannelSocketErrorInteract';
	var httpRequest = makeRequest(sendMessageURI,true);
};

onSocketOpen = function() {
	// socket opened
};

onSocketClose = function() {
	requestToken();
	var sendMessageURI = '/logger?code=2&status=ChannelSocketCloseInteract';
	var httpRequest = makeRequest(sendMessageURI,true);
};

onSocketMessage = function(message) {
	var messageXML =  ((new DOMParser()).parseFromString(message.data, "text/xml"));
	var messageType = messageXML.documentElement.getElementsByTagName("type")[0].firstChild.nodeValue;
	if (messageType == "updateMessage") {
		vidId = messageXML.documentElement.getElementsByTagName("vidId")[0].firstChild.nodeValue;
		newURL = updateURL(window.location.href, 'vidId', vidId);
		window.location = newURL;
	} else if (messageType == "eventMessage") {
		var event = messageXML.documentElement.getElementsByTagName("event")[0].firstChild.nodeValue;
		$.mobile.changePage($(event), { transition:"fade", changeHash:false });
	} 
};

//general ajax function for all requests 
function makeRequest(url,async) {
	var httpRequest;
	if (window.XMLHttpRequest) {
		// Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
	}

	if (!httpRequest) {
		alert('Cannot create an XMLHTTP instance');
		return false;
	}
	httpRequest.open('POST', url,async);
	httpRequest.send();
	return httpRequest;
}


function responseSubmit(reply, qId, viewer, redirect) {
	//Send the answer to the server
	var responseURI = '/response?reply=' + reply + '&qId=' + qId + '&viewer=' + viewer ;
	makeRequest(responseURI,true);
	
	//Get the points
	var points;
	for (i=0 ; i<pointsObject.length ; i++) {
		thisQuestion = pointsObject[i].question
		if (thisQuestion == qId) {
			points = pointsObject[i].points
		}
	}
	
	//Get the correct answer for this question from the ca array
	correct = ca[qId];
	//Update the response feedback
	if (reply == correct) {
		document.getElementById("responseFeedback-" + qId).innerHTML = 
			"You're right! You got " + points + " points! - the correct answer is in green.";
	} else {
		console.log("not equal");
		document.getElementById("responseFeedback-" + qId).innerHTML = 
			"You answered: " + reply + ".<br>\nSorry the correct answer is: " + correct + ", highlighted in green.";
	}
	//Redirect the page
	$.mobile.changePage($(redirect), { transition:"fade", changeHash:false });
}

function playVideo(videoId) {
	//Send TV and other devices the video ID to play
	var responseURI = '/comm?code=2&vidId=' + videoId;
	makeRequest(responseURI,true);
}

function playStop() {
	var responseURI = '/comm?code=3';
	makeRequest(responseURI,true);
}

function iniOptionsMenu() {
	$('#username-save').click(function() {
		continueTest = true;
		pattern = new RegExp("^[A-z0-9-]+$");
		//Get the username
		un = $('#username-input').attr('value');
		if (pattern.test(un) == false) {
			un = null;
			continueTest = false;
			$('#unError').text("Invalid characters. Only letters, numbers, and hypens are allowed");
		} else if (un.length > 30) {
			un = null;
			continueTest = false;
			$('#unError').text("Your user name is too long. Please limit your user name to 30 characters");
		}
		
		//Get the selected radio button
		rb = $("input[name*=radio-choice]:checked").val();
		
		if (continueTest == true || rb != null) {
			unSend = "";
			if (continueTest == true) {
				unSend = un;
			} else {
				unSend = rb;
			}
			//Submit the username for server validation
			dataString = "code=1&usern=" + unSend;
			$.ajax({
				type: "POST",
				url: "/tuser",
				data: dataString,
				success: function(data) {
					if (data.status == "ok") {
						//Name has been saved successfully
						$('#username-input').attr('placeholder', unSend)
						showSuccess();
					} else if (data.status == "in_use") {
						$('#unError').text("Name in use. Type another or select from below and press save");
						suggest = data.suggestions;
						
						//clear input field
						$('#username-input').attr('value', '');
						
						//Loop through the suggestions and apply to form
						nu = 1;
						for (n in suggest) {
							//Set the button text
							$('#radio-'+nu+'-label').children('.ui-btn-inner').children('.ui-btn-text').text(suggest[n]);
							console.log("set name as: ", suggest[n], " for id: ", nu);
							//Set the value
							$('#radio-choice-'+nu).attr('value', suggest[n]);
							nu++;
						}
						$('#unSuggestions').show();
					}
				},
				error: function() {
					$('#unError').text("Network error - please try again later");
				}
			});
		} else if (continueTest == true) {
			$('#unError').text("No username entered (your current username is above)");
		}
	});
}

function showSuccess() {
	$('#optSuccess').text("Username saved");
	$('#username-input').attr('value', '');
	$('#username-form').trigger('collapse');
	$('#unSuggestions').html("");
	$('#unError').text("");
}